<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','update','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
	  $model = $this->loadModel($id);
	  $profile = $this->loadModelProfile($id);
	  
	  $file_avatar = UserProfile::model()->getAvatar($id);
    $avatar = Yii::app()->baseUrl."/upload/avatar/thumbs_70x70/".$file_avatar;
    if($file_avatar=="") {
      $avatar = Yii::app()->baseUrl."/images/no-image.jpg";
    }
		$this->render('view',array(
			'model'=>$model, 'profile'=>$profile, 'avatar'=>$avatar
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User('create');
		$profile = new UserProfile('create');
		
		$model->roleID = 6;
		$profile->gender = 1;
		if(isset($_POST['User']) && isset($_POST['UserProfile']))
		{ 
			$model->attributes=$_POST['User'];
			$profile->attributes=$_POST['UserProfile'];
			$validate1 = $model->validate();
			$validate2 = $profile->validate();
			$model->active=1;
			
			if($validate1 && $validate2) {
			  if($_POST['User']['password']!='') {
					$model->password = md5($_POST['User']['password']);
				}					
				if($_POST['UserProfile']['dateofbirth']!='') {						 
					$profile->dateofbirth = strtotime($_POST['UserProfile']['dateofbirth']);		
				}
				if($model->save(false)) {
				  $profile->userID = $model->ID;
						
					if(CUploadedFile::getInstanceByName('UserProfile[avatar]')) { 
						$avatar = new File();
						$photo = CUploadedFile::getInstanceByName('UserProfile[avatar]');
						$avatar->filename = $photo->getName();
			    	$avatar->filesaved = encodeFilename(time().'_'.$photo->getName());
			    	$avatar->filetype =  $photo->getType();
			    	$avatar->folder = 'avatar';
			    	$photo->saveAs('upload/avatar/'.$avatar->filesaved);
			    	$avatar->save();
			    	$profile->avatar = $avatar->ID;
			    	//thumbnail 
			    	$thumb = Yii::app()->image->load(Yii::getPathOfAlias("webroot")."/upload/avatar/".$avatar->filesaved);
            $thumb->resize(70, 70);
            $thumb->save(Yii::getPathOfAlias("webroot")."/upload/avatar/thumbs_70x70/".$avatar->filesaved);//save vao thumb
					}
					
					// save user profile
					$profile->save(false);
					
					// insert user role record
					if(isset($_POST['User']['roleID']) && !empty($_POST['User']['roleID'])) {
					  $roles = $_POST['User']['roleID'];
					  foreach ($roles as $r) {
  					  $user_role = new UserRole();
    					$user_role->userID = $model->ID;
    					$user_role->roleID = $r;
    					$user_role->save(false);
					  }
					}
					
					// insert user status
					$user_status = new UserStatus();
					$statusID = Status::model()->findByAttributes(array('status'=>'OFFLINE'))->statusID;
					$user_status->statusID =$statusID;
					$user_status->userID = $model->ID;
					$user_status->save(false);
					
					// Insert user balance record
					$user_balance = new UserBalance();
					$user_balance->userID=$model->ID;
					$user_balance->balance=0;
					$user_balance->promotion=0;
					$user_balance->save(false);
					
					Yii::app()->user->setFlash('success',"Tạo mới thành công");
					unset($_POST);
  				$this->redirect(array('view','id'=>$model->ID));
				}
			}
		}

		$this->render('create',array(
			'model'=>$model, 'profile'=>$profile
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$profile = $this->loadModelProfile($id);
    
		if($profile->dateofbirth != '')
				$profile->dateofbirth = date("d-m-Y",$profile->dateofbirth);
		
		$model->password = "";
		$all_role = UserRole::model()->findAllByAttributes(array('userID'=>$id));
		$array_role = array();
		if(!empty($all_role)) {
		  foreach ($all_role as $r) {
		    $array_role[] = $r->roleID;
		  }
		  $model->roleID = $array_role;
		}
		else {
		  $model->roleID = 6;
		}
		$file_avatar = UserProfile::model()->getAvatar($id);
    $img_avatar = "";
	  if(isset($_POST['User']) && isset($_POST['UserProfile']))
		{ 
			$model->attributes=$_POST['User'];
			$profile->attributes=$_POST['UserProfile'];
			$model->setScenario('update');
			$validate1 = $model->validate();
			$validate2 = $profile->validate();
			if($validate1 && $validate2) {
			  if($_POST['User']['password']!='') {
					$model->password = md5($_POST['User']['password']);
				}		
				else {
				  $model->password = User::model()->findByPk($id)->password;
				}			
				if($_POST['UserProfile']['dateofbirth']!='') {						 
					$profile->dateofbirth = strtotime($_POST['UserProfile']['dateofbirth']);		
				}
				if($model->save(false)) {
				  $profile->userID = $model->ID;
						
				  if(CUploadedFile::getInstanceByName('UserProfile[avatar]')) { 
					  if(!empty($file_avatar)) {
					    $f = File::model()->findByAttributes(array('filesaved'=>$file_avatar));
  					  if(!empty($f)) {
      	        if(file_exists(Yii::app()->basePath.'/../upload/avatar/'.$file_avatar)) {
      	          @unlink(Yii::getPathOfAlias("webroot").'/upload/avatar/'.$file_avatar);
      	        }
      	        if(file_exists(Yii::app()->basePath.'/../upload/avatar/thumbs_70x70/'.$file_avatar)) {
      	          @unlink(Yii::getPathOfAlias("webroot").'/upload/avatar/thumbs_70x70/'.$file_avatar);
      	        }
      	        $f->delete();
      	      }					    
					  }
						$avatar = new File();
						$photo = CUploadedFile::getInstanceByName('UserProfile[avatar]');
						$avatar->filename = $photo->getName();
			    	$avatar->filesaved = encodeFilename(time().'_'.$photo->getName());
			    	$avatar->filetype =  $photo->getType();
			    	$avatar->folder = 'avatar';
			    	$photo->saveAs('upload/avatar/'.$avatar->filesaved);
			    	$avatar->save();
			    	$profile->avatar = $avatar->ID;
			    	//thumbnail 
			    	$thumb = Yii::app()->image->load(Yii::getPathOfAlias("webroot")."/upload/avatar/".$avatar->filesaved);
            $thumb->resize(70, 70);
            $thumb->save(Yii::getPathOfAlias("webroot")."/upload/avatar/thumbs_70x70/".$avatar->filesaved);//save vao thumb
					}
					
					// save user profile
					$profile->save(false);
					
					// insert user role record
					if(isset($_POST['User']['roleID']) && !empty($_POST['User']['roleID'])) {
					  if(!empty($all_role)) {
					    UserRole::model()->deleteAllByAttributes(array('userID'=>$id));
					  }
					  $roles = $_POST['User']['roleID'];
					  foreach ($roles as $r) {
  					  $user_role = new UserRole();
    					$user_role->userID = $model->ID;
    					$user_role->roleID = $r;
    					$user_role->save(false);
					  }
					}
					
					Yii::app()->user->setFlash('success',"Cập nhật thành công");
					unset($_POST);
  				$this->redirect(array('view','id'=>$model->ID));
				}
			}
		}
	  if(!empty($file_avatar)) {
      $img_avatar = Yii::app()->baseUrl."/upload/avatar/thumbs_70x70/".$file_avatar;
    }

		$this->render('update',array(
			'model'=>$model, 'profile'=>$profile, 'img_avatar'=>$img_avatar
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			$model->deleted = 1;
			$model->update();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	/*public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}*/

/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];		

		$this->render('index',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	public function loadModelProfile($id)
	{
		$model=UserProfile::model()->findByAttributes(array('userID'=>$id));
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist2.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
